package com.kung.qvs.ui.main.fragment;

import static com.kung.qvs.BuildConfig.DEBUG;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.Navigation;

import com.kung.qvs.BR;
import com.kung.qvs.R;
import com.kung.qvs.app.AppViewModelFactory;
import com.kung.qvs.databinding.FragmentBleDeviceListBinding;
import com.kung.qvs.ui.main.HomeActivity;
import com.kung.qvs.ui.main.KungViewModel;
import com.kung.qvs.ui.widget.SpacesItemDecoration;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class BleDeviceListFragment extends BaseFragment<FragmentBleDeviceListBinding, BleDeviceViewModel> {
    private String TAG = BleDeviceListFragment.class.getSimpleName();
    public static final int REQUEST_PERMISSION_LOCATION = 2;
    public static final int REQUEST_PERMISSION_WRITE = 3;
    public static final int REQUEST_GPS = 4;

    //    private List<BleRssiDevice> bleRssiDevices;
//    private Ble<BleRssiDevice> ble = Ble.getInstance();
    private ObjectAnimator animator;

    private HomeActivity homeActivity;
    private KungViewModel kungViewModel;
    private boolean isScaning = false;  //是否在扫描设备

    private BluetoothAdapter mBtAdapter;

    private String bleType = "";

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_ble_device_list;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public BleDeviceViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(getActivity(), factory).get(BleDeviceViewModel.class);
    }

    @Override
    public void initParam() {
        super.initParam();
        Bundle mBundle = getArguments();
        if (mBundle != null) {
            bleType = mBundle.getString("bleType");
        }
    }

    @Override
    public void initData() {
        super.initData();
        homeActivity = (HomeActivity) getActivity();

        kungViewModel = new ViewModelProvider(getActivity()).get(KungViewModel.class);
        kungViewModel.setmIsHomeFrag(false);

        binding.floatingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startScan();
            }
        });

        binding.rv.addItemDecoration(new SpacesItemDecoration(10));

        // 注册蓝牙搜索广播
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        getActivity().registerReceiver(mReceiver, filter);

        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        initBleStatus();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //连接蓝牙
        viewModel.uc.toConnectBle.observe(this, new Observer<BluetoothDevice>() {
            @Override
            public void onChanged(BluetoothDevice bleDevice) {
                if (bleDevice == null) return;
                if (mBtAdapter != null) {
                    mBtAdapter.cancelDiscovery();
                }

                if (!StringUtils.isTrimEmpty(bleType) && "printer".equals(bleType)) {
//                    homeActivity.ConnectBTDevicePrint(bleDevice);
                } else {
//                    homeActivity.ConnectBleDevice(bleDevice);
                }
                Navigation.findNavController(getView()).navigateUp();
            }
        });

        viewModel.uc.toPageUp.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                Navigation.findNavController(getView()).navigateUp();
            }
        });

        //监听下拉刷新完成
        viewModel.uc.finishRefreshing.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.recyclingRL.finishRefreshing();
            }
        });
        //监听上拉加载完成
        viewModel.uc.finishLoadmore.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
//                rescan();
                binding.recyclingRL.finishLoadmore();
            }
        });
    }

    //请求权限
//    @Permission(value = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
//            requestCode = REQUEST_PERMISSION_LOCATION,
//            rationale = "需要蓝牙相关权限")
//    public void requestPermission() {
//        checkBlueStatus();
//    }

    //监听蓝牙开关状态
    private void initBleStatus() {
        startScan();
    }

    private void startScan() {

        if(isScaning){
            ToastUtils.showShort("正在扫描设备");
            return;
        }

        if (DEBUG) Log.d(TAG, "doDiscovery()");

        // 设置标题栏进程条可见
        isScaning = true;
        binding.tvTips.setVisibility(View.VISIBLE);
        startBannerLoadingAnim();

        // 当正在搜索，则停止搜索
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
            isScaning = false;
            binding.tvTips.setVisibility(View.GONE);
            stopBannerLoadingAnim();
        }
        // 否则开启蓝牙搜索
        else{
            isScaning = true;
            binding.tvTips.setVisibility(View.VISIBLE);
            startBannerLoadingAnim();
            //清空新搜索到设备的列表以免重复添加
            viewModel.observableList.clear();
            viewModel.notifyDataSetChanged();
            // 开始搜索设备
            mBtAdapter.startDiscovery();
        }
    }


//    private void rescan() {
//        try{
//            BleManager.getInstance().cancelScan();
//        }catch (NullPointerException e){
//            e.printStackTrace();
//        }
//        Handler handler = new Handler();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                // 执行的操作
//                scan();
//            }
//        }, 300);//300毫秒后执行Runnable中的run方法
//
//    }

//    String fliterName = "J";

    public void startBannerLoadingAnim() {
        binding.floatingButton.setImageResource(R.drawable.ic_loading);
        if (animator == null) {
            animator = ObjectAnimator.ofFloat(binding.floatingButton, "rotation", 0, 360);
            animator.setRepeatCount(ValueAnimator.INFINITE);
            animator.setDuration(800);
            animator.setInterpolator(new LinearInterpolator());
        }
        animator.start();
    }

    public void stopBannerLoadingAnim() {
        binding.floatingButton.setImageResource(R.drawable.ic_bluetooth_audio_black_24dp);
        if (animator != null) {
            animator.cancel();
        }
//        binding.floatingButton.setRotation(0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        // User chose not to enable Bluetooth.
//        if (requestCode == Ble.REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
////            finish();
//        } else if (requestCode == Ble.REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
//            ble.startScan(scanCallback);
//        } else if (requestCode == REQUEST_GPS) {
//
//        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 取消可 能存在的搜索
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }
        // 注销蓝牙广播
        getActivity().unregisterReceiver(mReceiver);
    }

    // 蓝牙广播
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 发现设备
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device ;
                // 获取蓝牙设备
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 已匹配的跳过
//                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
//                    mNewDevices.add(device.getName() + "\n" + device.getAddress());
//                }
                //将扫描到的都加入
                for (int i = 0; i < viewModel.observableList.size(); i++) {
                    BluetoothDevice rssiDevice = viewModel.observableList.get(i).entity.get();
                    if (TextUtils.equals(rssiDevice.getAddress(), device.getAddress())) {
//                                rssiDevice.setRssi(device.getRssi());
                        viewModel.notifyItemChanged(i);
                        return;
                    }
                }
                if (!StringUtils.isTrimEmpty(device.getName())) {
                    viewModel.addBleDevice(device);
                    viewModel.notifyDataSetChanged();
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //蓝牙搜索完成
                if (viewModel.observableList.size() == 0) {
                    viewModel.observableList.clear();
                    viewModel.notifyDataSetChanged();
                }

                isScaning = false;
                binding.tvTips.setVisibility(View.GONE);
                stopBannerLoadingAnim();
            }
        }
    };
}
